package com.superman.supermarket.client.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.google.gwt.event.shared.EventBus;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.user.client.Window;
import com.google.inject.Inject;
import com.superman.mvpframe.client.ajax.PostManAsyncCallBack;
import com.superman.mvpframe.client.event.ToastEvent;
import com.superman.mvpframe.client.mvp.IPageView;
import com.superman.mvpframe.client.mvp.IPageViewPresenter;
import com.superman.mvpframe.client.utils.Registry;
import com.superman.mvpframe.client.utils.XJsonUtil;
import com.superman.mvpframe.client.widget.pop.BasePopupWindow;
import com.superman.supermarket.client.composite.sku.pop.SkuPropSelectModule;
import com.superman.supermarket.client.composite.sku.pop.SkuPropSelectModule.HideCallBack;
import com.superman.supermarket.client.event.SkuPageEvent;
import com.superman.supermarket.client.mvp.ShopAbstractActivity;
import com.superman.supermarket.client.utils.ActivityJumpUrl;
import com.superman.supermarket.client.view.sku.SKUView;
import com.superman.supermarket.client.view.sku.SKUView.SKUViewPresenter;

/**
 * 商品详情Activity
 * 
 * @author superman
 * @version 2018年7月23日下午9:26:51
 */
public class SKUActivity extends ShopAbstractActivity implements SKUViewPresenter {

	private Map<String, Object> skuDetailMap;

	private SKUView skuView;
	private String spuId, prop;

	/**
	 * 构造方法
	 * 
	 * @author superman
	 * @version 2018年8月21日 下午4:15:58
	 * @param skuView
	 */
	@Inject
	public SKUActivity(SKUView skuView) {
		this.skuView = skuView;
	}

	private void addToCart(String skuId, int num) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("SKU_ID", skuId);
		map.put("SKU_NUM", num);
		postman.post("cart/add", map, new PostManAsyncCallBack() {

			@Override
			public void onBusinessError(String statusCode) {

			}

			@Override
			public void onBusinessOK(String response) {
				eventBus.fireEvent(new ToastEvent("已添加到购物车"));
			}
		});
	}

	private void buy(String skuId, int num) {
		Map<String, Object> skuMap = new HashMap<String, Object>();
		skuMap.put("SKU_ID", skuId);
		skuMap.put("SKU_NUM", num);

		List<Map<String, Object>> skuList = new ArrayList<Map<String, Object>>();
		skuList.add(skuMap);

		Map<String, Object> skuStoreMap = new HashMap<String, Object>();
		skuStoreMap.put("STORE_ID", skuDetailMap.get("STORE_ID"));
		skuStoreMap.put("SKU_LIST", skuList);

		List<Map<String, Object>> storeList = new ArrayList<Map<String, Object>>();
		storeList.add(skuStoreMap);

		final Map<String, Object> postMap = new HashMap<String, Object>();
		postMap.put("STORE_SKU_LIST", storeList);

		postman.post("order/settlement2", postMap, new PostManAsyncCallBack() {

			@Override
			public void onBusinessError(String statusCode) {

			}

			@Override
			public void onBusinessOK(String response) {
				Registry.register("settlementinfo", XJsonUtil.getBody(response));
				Registry.register("preorderinfo", postMap);
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("CLEAN_CART", 0);
				placeController.push(placeFactory.getPreorderPlace(), map);
			}
		});
	}

	private void changeFavStatus(final boolean collect) {
		Map<String, Object> map = new HashMap<String, Object>();
		List<String> spus = new ArrayList<String>();
		spus.add(spuId);
		map.put("SPU_IDS", spus);
		postman.post(collect ? "favorite/add" : "favorite/delete", map, new PostManAsyncCallBack() {

			@Override
			public void onBusinessError(String statusCode) {

			}

			@Override
			public void onBusinessOK(String response) {
				eventBus.fireEvent(new ToastEvent(collect ? "已收藏" : "已取消收藏"));
				skuView.changeFavStatus(collect);
			}
		});
	}

	private void getSkuDetail() {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("SPU_ID", spuId);
		postman.post("goods/detail", map, new PostManAsyncCallBack() {

			@Override
			public void onBusinessError(String statusCode) {

			}

			@Override
			public void onBusinessOK(String response) {
				skuDetailMap = XJsonUtil.getBody(response);

				// 解析商品的基本信息
				parseSkuBaseInfo();
				// 解析商品图片
				parseSkuImages();
				// 解析商品的可用的一个优惠券计划
				parseCouponItem();
				// 解析商品配送信息
				parseDeliveryInfo();
				// 解析评论
				parseCommentList();
				// 解析店铺的信息
				parseStoreInfo();
				// 解析图文详情
				parseSkuPicDetail();
			}
		});
	}

	@Override
	public IPageView getView() {
		return skuView;
	}

	@Override
	public IPageViewPresenter getViewPresenter() {
		return this;
	}

	@Override
	public void onActivity(EventBus eventBus) {
		eventBus.addHandler(SkuPageEvent.TYPE, new SkuPageEvent.SkuPageEventHandler() {

			@Override
			public void collect() {
				changeFavStatus(true);
			}

			@Override
			public void showPopToAddCart() {
				final BasePopupWindow basePopupWindow = new BasePopupWindow();
				SkuPropSelectModule skuPropSelectModule = new SkuPropSelectModule(new HideCallBack() {

					@Override
					public void close(Map<String, Object> skuM, String selectedProp, int num) {
						prop = selectedProp;
						parseSkuBaseInfo();
						basePopupWindow.hide();
					}

					@Override
					public void submit(Map<String, Object> skuM, String selectedProp, int num) {
						prop = selectedProp;
						parseSkuBaseInfo();
						basePopupWindow.hide();
						addToCart(String.valueOf(skuM.get("skuid")), num);
					}
				});
				skuPropSelectModule.setData(skuDetailMap, prop);
				basePopupWindow.add(skuPropSelectModule);
				basePopupWindow.bottom();
			}

			@Override
			public void showPopToBuy() {
				final BasePopupWindow basePopupWindow = new BasePopupWindow();
				SkuPropSelectModule skuPropSelectModule = new SkuPropSelectModule(new HideCallBack() {

					@Override
					public void close(Map<String, Object> skuM, String selectedProp, int num) {
						prop = selectedProp;
						parseSkuBaseInfo();
						basePopupWindow.hide();

					}

					@Override
					public void submit(Map<String, Object> skuM, String selectedProp, int num) {

						prop = selectedProp;
						parseSkuBaseInfo();
						basePopupWindow.hide();
						buy(String.valueOf(skuM.get("skuid")), num);

					}
				});
				skuPropSelectModule.setData(skuDetailMap, prop);
				basePopupWindow.add(skuPropSelectModule);
				basePopupWindow.bottom();
			}

			@Override
			public void uncollect() {
				changeFavStatus(false);

			}
		});
	}

	private void parseCommentList() {
		List<Map<String, Object>> commentStar = XJsonUtil.getList((JSONArray) skuDetailMap.get("COMMENT_STAT"));
		int totalCount = 0;
		for (Map<String, Object> map : commentStar) {
			int type = (int) Double.parseDouble(String.valueOf(map.get("TYPE")));
			int count = (int) Double.parseDouble(String.valueOf(map.get("COUNT")));

			if (type == 0) {
				totalCount = count;
				break;
			}
		}

		if (totalCount == 0) {
			skuView.removeCommentListModule();
		} else {
			List<Map<String, Object>> commentList = XJsonUtil.getList((JSONArray) skuDetailMap.get("COMMENT_LIST"));
			skuView.setCommentCountAndCommentList(totalCount, commentList);
		}
	}

	private void parseCouponItem() {
		if (skuDetailMap.get("COUPON_ITEM") == null)
			skuView.setCouponInfo(null);
		else
			skuView.setCouponInfo(XJsonUtil.getMap((JSONObject) skuDetailMap.get("COUPON_ITEM")));
	}

	private void parseDeliveryInfo() {
		String dispathAddr = String.valueOf(skuDetailMap.get("DISPATCH_ADDR"));

		Map<String, Object> postFeeMap = XJsonUtil.getMap((JSONObject) skuDetailMap.get("POSTAL_FEES"));

		StringBuffer postFeeStr = new StringBuffer();

		Set<String> set = postFeeMap.keySet();
		Iterator<String> it = set.iterator();
		while (it.hasNext()) {
			Object obj = it.next();

			postFeeStr.append(String.valueOf(obj));
			postFeeStr.append(":");
			postFeeStr.append(postFeeMap.get(obj) + "元");
			postFeeStr.append(" ");
		}

		skuView.setDeliveryInfo(dispathAddr, postFeeStr.toString());
	}

	private void parseSkuBaseInfo() {
		String skuName = String.valueOf(skuDetailMap.get("NAME"));
		String desc = String.valueOf(skuDetailMap.get("DESCRIPTION"));
		double salePrice = 0;
		double listPrice = 0;
		boolean isFav = Double.parseDouble(String.valueOf(skuDetailMap.get("IS_FAVORITE"))) == 1;

		if (this.prop == null) {
			// 没有默认属性的时候,商品的价格区spu的价格
			salePrice = Double.parseDouble(String.valueOf(skuDetailMap.get("SALE_PRICE")));
			listPrice = Double.parseDouble(String.valueOf(skuDetailMap.get("LIST_PRICE")));
			skuView.setDetailPropNames("请选择商品");
		} else {
			// 当有默认的属性的时候,商品的价格取sku的价格
			Map<String, Object> skuMap = XJsonUtil.getMap((JSONObject) skuDetailMap.get("SKU_MAP"));
			Map<String, Object> skuNameMap = XJsonUtil.getMap((JSONObject) skuMap.get(prop));
			String skuNames = String.valueOf(skuNameMap.get("prop_names"));
			salePrice = Double.parseDouble(String.valueOf(skuNameMap.get("sale_price")));
			listPrice = Double.parseDouble(String.valueOf(skuNameMap.get("list_price")));
			skuView.setDetailPropNames(skuNames);
		}

		skuView.setSkuNameAndOtherInfo(skuName, desc, salePrice, listPrice, isFav);
	}

	private void parseSkuImages() {
		JSONArray images = (JSONArray) skuDetailMap.get("IMAGES");
		skuView.setSkuImages(XJsonUtil.getStrList(images));
	}

	protected void parseSkuPicDetail() {
		if (skuDetailMap.get("DETAIL_URL") == null) {
			skuView.removePicDetailModule();
		} else {
			String detailUrl = String.valueOf(skuDetailMap.get("DETAIL_URL"));
			RequestBuilder requestBuilder = new RequestBuilder(RequestBuilder.GET, detailUrl);
			requestBuilder.setCallback(new RequestCallback() {

				@Override
				public void onError(Request request, Throwable exception) {

				}

				@Override
				public void onResponseReceived(Request request, Response response) {
					skuView.setPicDetailHTML(response.getText());
				}
			});

			try {
				requestBuilder.send();
			} catch (RequestException e) {
				e.printStackTrace();
			}
		}
	}

	protected void parseStoreInfo() {
		String storeLogo = String.valueOf(skuDetailMap.get("STORE_LOGO"));
		String storeName = String.valueOf(skuDetailMap.get("STORE_NAME"));
		String storeId = String.valueOf(skuDetailMap.get("STORE_ID"));
		skuView.setStoreInfo(storeId, storeLogo, storeName);
	}

	@Override
	public void popToRefresh() {
		// TODO Auto-generated method stub
	}

	@Override
	public void popToRefresh(Object contextData) {
		// TODO Auto-generated method stub

	}

	@Override
	public void pushToCommentListPage() {
		ActivityJumpUrl.pushToCommentListaPage(spuId);
	}

	@Override
	public void pushToRefresh() {
		this.spuId = Window.Location.getParameter("spuid");
		this.prop = Window.Location.getParameter("prop");

		getSkuDetail();
	}

	@Override
	public void pushToStoreCouponListPage() {
		ActivityJumpUrl.pushToStoreCouponListPage(String.valueOf(skuDetailMap.get("STORE_ID")));
	}

}
